package com.csxh.web.userinfo.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csxh.web.userinfo.bean.User;
import com.csxh.web.userinfo.service.UserService;
import com.csxh.web.userinfo.util.WebUtil;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login.servlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	  //获取传过来的参数：约定：表单的名称与User bean的属性相同
	  Map<String,String[]> map=request.getParameterMap();
	  String name=map.get("name")[0];
	  String password=map.get("password")[0];
	  
	  //登录处理：交给业务层完成
	  UserService service=new UserService();
	  User u=service.findUser(name, password);
	  
	  response.setCharacterEncoding("utf-8");
	  
	  if(null!=u){
		  //System.out.println("登录成功");
		  //登录成功，将用户对象保存到用户级别的上下文对象中，用于检验是否已经登录的标记
		  WebUtil.saveLoginUser(request,u);
		  
		  //在转向到首页前包含页页的servlet,以便获取数据
		  request.getRequestDispatcher("index.servlet").include(request, response);
		  
		  request.getRequestDispatcher("index.jsp").forward(request, response);
		  
	  }else{
		  //System.out.println("登录失败");
		  //转向登录页
		  request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
	  }
		
	}

}
